package org.iartisan.thought.web.tag;

import com.sun.media.sound.SoftTuning;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.iartisan.runtime.bean.Page;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.text.MessageFormat;
import java.util.Map;

/**
 * <p>
 * 分页
 *
 * @author King
 * @since 2017/12/20
 */
@Component
public class PageDirective implements TemplateDirectiveModel {


    private static final String urlPattern = "<a href={0}?currPage={1}>{2}</a>";

    private static final String currentPattern = "<span class='laypage-curr'>{0}</span>";

    private static final String end_page_urlPattern = "<a href='{0}'>尾页</a>";

    private static final String next_page_urlPattern = "<a href='{0}'>下一页</a>";

    private static final String pre_page_urlPattern = "<a href='{0}'>上一页</a>";

    private static final String start_page_urlPattern = "<a href='{0}'>首页</a>";

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        Writer out = environment.getOut();
        int currPage = Integer.parseInt(map.get("currPage").toString());
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        int totalPage = Integer.parseInt(map.get("totalPage").toString());
        TemplateModel url = (TemplateModel) map.get("url");
        StringBuffer buffer = new StringBuffer();
        String first = null;
        String middle;
        String end;
        if (currPage < 5) {
            for (int i = 1; i < totalPage + 1; i++) {
                if (i == currPage) {
                    buffer.append(MessageFormat.format(currentPattern, i));
                } else {
                    buffer.append(MessageFormat.format(urlPattern, url, i, i));
                }
            }
        }
        if (totalPage >= 5) {

        }

        out.write(buffer.toString());
        templateDirectiveBody.render(out);
    }
}
